# Openpose
# Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
# 2nd Edited by https://github.com/Hzzone/pytorch-openpose
# 3rd Edited by ControlNet
# 4th Edited by ControlNet (added face and correct hands)

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

import torch
import numpy as np
from . import util
from .wholebody import Wholebody

def draw_pose(pose, H, W):
    bodies = pose['bodies']
    faces = pose['faces']
    hands = pose['hands']
    candidate = bodies['candidate']
    subset = bodies['subset']
    canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)

    canvas = util.draw_bodypose(canvas, candidate, subset)

    canvas = util.draw_handpose(canvas, hands)

    # canvas = util.draw_facepose(canvas, faces)

    return canvas

MODULE_DIR = os.path.dirname(os.path.abspath(__file__))


class DWposeDetector:
    def __init__(self,
        onnx_det: str = os.path.join(MODULE_DIR, "..","ckpts/yolox_l.onnx" ),
        onnx_pose: str = os.path.join(MODULE_DIR, "..","ckpts/dw-ll_ucoco_384.onnx" ),
        device: str = "cuda:0"
        ):

        self.pose_estimation = Wholebody(onnx_det=onnx_det,onnx_pose=onnx_pose,device=device)

    def __call__(self, oriImg,body_threshold=0.3,other_threshold=0.3,is_discard=False,only_one=False):
        oriImg = oriImg.copy()
        H, W, C = oriImg.shape
        with torch.no_grad():
            candidate, subset = self.pose_estimation(oriImg)
            if candidate.shape[0]>1 and only_one:
                
                print(f"because of only one, candidate shape:{candidate.shape}->")
                candidate = candidate[0].reshape(1,134,2)
                print(candidate.shape)
                print(f"because of only one, subset shape:{subset.shape}->")
                subset = subset[0].reshape(1,134)
                print(subset.shape)
            
            #print(candidate)
            nums, keys, locs = candidate.shape # 人物，134个关键点，识别的坐标
            candidate[..., 0] /= float(W)
            candidate[..., 1] /= float(H)
            body = candidate[:,:18].copy()
            body = body.reshape(nums*18, locs)
            score = subset[:,:18]
            #print(subset.shape)
            #print(subset)
            #print(score)
            for i in range(len(score)):
                for j in range(len(score[i])):
                    if score[i][j] > body_threshold:
                        score[i][j] = int(18*i+j)
                    else:
                        score[i][j] = -1

            #==========================
            #print(score)
            count = np.sum(score==-1)
            if count>=6 and is_discard:
                print("跳过",count)
                return None
            #==========================
            #print(score)
            un_visible = subset< other_threshold
            candidate[un_visible] = -1

            foot = candidate[:,18:24]

            faces = candidate[:,24:92]

            hands = candidate[:,92:113]
            hands = np.vstack([hands, candidate[:,113:]])
            
            bodies = dict(candidate=body, subset=score)
            pose = dict(bodies=bodies, hands=hands, faces=faces)

            return draw_pose(pose, H, W)
